package br.odb.libsvg;

import java.io.OutputStream;
import java.util.ArrayList;

import br.odb.libscene.Color;
import br.odb.utils.math.Vec2;

/**
 * 
 * @author Daniel "Monty" Monteiro
 */
public class ColoredPolygon {
	public Color color;
	public String originalStyle;
	public float[] xpoints;
	public float[] ypoints;
	public int npoints;
	private ArrayList<Vec2> points;
	public ArrayList<Vec2> controlPoints;

	public ColoredPolygon() {
		color = new Color();
		points = new ArrayList<Vec2>();
		controlPoints = new ArrayList<Vec2>();
	}

	public String getSVGString() {
		int n;
		String toReturn = "";

		if (this.npoints <= 0)
			return toReturn;
		
		

		toReturn = "<path style='";
		toReturn += originalStyle;
		toReturn += "' d='";
		toReturn += " M ";
		toReturn += xpoints[0];
		toReturn += ",";
		toReturn += ypoints[0];

		for (int c = 0; c < npoints; ++c) {

			n = c % (this.npoints);
			toReturn += " L ";
			toReturn += (this.xpoints[n]);
			toReturn += ",";
			toReturn += (this.ypoints[n]);
		}

		toReturn += " z' />\n";
		return toReturn;
	}

	public void writePath( OutputStream os ) {
		byte[] bytes = new byte[10];
		bytes[0] = (byte) (color.getA() - Byte.MIN_VALUE);
		bytes[1] = (byte) (color.getR() - Byte.MIN_VALUE);
		bytes[2] = (byte) (color.getG() - Byte.MIN_VALUE);
		bytes[3] = (byte) (color.getB() - Byte.MIN_VALUE);
		int range = Byte.MAX_VALUE - Byte.MIN_VALUE;
		bytes[4] = (byte) (((this.xpoints[0] * range) / 800) - Byte.MIN_VALUE);
		bytes[5] = (byte) (((this.ypoints[0] * range) / 480) - Byte.MIN_VALUE);

		bytes[6] = (byte) (((this.xpoints[1] * range) / 800) - Byte.MIN_VALUE);
		bytes[7] = (byte) (((this.ypoints[1] * range) / 480) - Byte.MIN_VALUE);

		bytes[8] = (byte) (((this.xpoints[2] * range) / 800) - Byte.MIN_VALUE);
		bytes[9] = (byte) (((this.ypoints[2] * range) / 480) - Byte.MIN_VALUE);

		try {
			os.write(bytes);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void addPoint(float x, float y) {
		Vec2 p = new Vec2();
		p.x = x;
		p.y = y;
		points.add( p );
		p = new Vec2();
		controlPoints.add( p );
		p.invalidate();
		updateState();
	}

	private void updateState() {
		npoints = points.size();

		xpoints = new float[npoints];
		ypoints = new float[npoints];
		Vec2 v;
		for (int c = 0; c < npoints; ++c) {
			v = points.get( c );
			xpoints[c] = v.x;
			ypoints[c] = v.y;
		}
	}

	public void buildStyleProperty() {
		
		if ( color == null )
			return;
		
		originalStyle = "fill:" + color.getHTMLColor() + ";";
		
		if ( color.getA() != 255 ) {
			originalStyle += "opacity: " + ( color.getA() / 255.0f ) + ";";
		}
	}
}
